var map = null;
var geocoder;
var base_url;//= "http://localhost/cellplan/";
var site_url;//= "http://localhost/cellplan/index.php/";

var polyPathdesa = [];
var polyPathkec = [];

var kecPath = [];

var polyHoverDes = [];
var polyHoverkec = [];

var bound_kec = [];

var list_page_chart = [];
list_page_chart[''] = '';
//base_url = document.getElementById("base_url").value;

var page_chart = '';//base_url+'index.php/jenis_kelamin/chart';
//console.log('init base_url');
function set_page_chart(p) {
    page_chart = base_url + 'index.php/pendidikan/' + p;
    console.log(page_chart);
}
var datac = {};
function set_data_chart(d) {
    datac = d;
}
function load_chart() {
    $.ajax({
        url: page_chart,
        type: "post",
        data: datac,
        beforeSend: function() {
            $('.kotakdata').html('<img src="' + base_url + '/static/images/loading.gif" alt="Loading data Kependudukan" border="0" style="margin-left:25%; margin-top:10%" width="300px">');
        },
        success: function(response) {
            $('.kotakdata').html(response);
        }
    });
}



$(document).ready(function() {

    $('#pilihdata').change(function() {
        console.log('pilih data');
        var val = $('#pilihdata option:selected').val();
        set_page_chart(val);
        load_chart();
    });
});


google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow;

//var markers_tower = [];


function initialize() {
    base_url = document.getElementById("base_url").value;
    site_url = document.getElementById("site_url").value;
    infoWindow = new google.maps.InfoWindow();
    set_page_chart('chart_peserta_didik');
    load_chart();

    var myOptions = {
        zoom: 11,
        center: new google.maps.LatLng(-8.219021, 114.369105),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_LEFT
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.LEFT_BOTTOM
        },
        panControl: true,
        panControlOptions: {
            position: google.maps.ControlPosition.LEFT_BOTTOM
        },
        streetViewControl: false

    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    draw_poly_kec();
    //draw_poly_desa();



    $('#pilihkecamatan').change(function() {
        var id = $('#pilihkecamatan option:selected').val();
        console.log('id kecamatan = ' + id);
        set_data_chart({id_kecamatan: id});
        load_chart();

        document.getElementById("id_kec").value = id;
        clear_layer_all(kecPath);
        clear_layer_all(polyPathdesa);
        draw_poly_kec();
        //draw_poly_desa();

        map.fitBounds(bound_kec[id]);
    });
}


function add_polygon_desa(poly_data_lgkp, index) {
    var titik_poly = [];
    var point_label;


    var poly_data = poly_data_lgkp.DESA_POINT_LIST;
    for (var a = 0; a < poly_data.length - 1; a++) {
        titik_poly[a] = new google.maps.LatLng(poly_data[a].LAT, poly_data[a].LNG);
    }
    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < titik_poly.length; i++) {
        bounds.extend(titik_poly[i]);
    }

    polyPathdesa[index] = new google.maps.Polygon({
        paths: titik_poly,
        strokeColor: "#333333",
        strokeOpacity: 0.9,
        strokeWeight: 0.2,
        fillColor: poly_data_lgkp.COLOR,
        fillOpacity: 0.2
    });

    polyHoverDes[index] = new google.maps.Polygon({
        paths: titik_poly,
        strokeColor: "#333333",
        strokeOpacity: 1,
        strokeWeight: 0.3,
        fillColor: "#000000",
        fillOpacity: 0.7
    });

    var marker_ = new MarkerWithLabel({
        position: new google.maps.LatLng(0, 0),
        draggable: false,
        raiseOnDrag: false,
        map: map,
        labelContent: poly_data_lgkp.DESA_NAMA + " | " + poly_data_lgkp.KECAMATAN_NAMA,
        labelAnchor: new google.maps.Point(30, 20),
        labelClass: "labels", // the CSS class for the label
        labelStyle: {opacity: 1.0},
        icon: "http://placehold.it/1x1",
        visible: false
    });

    google.maps.event.addListener(polyPathdesa[index], "mousemove", function(event) {

        marker_.setPosition(event.latLng);
        marker_.setVisible(true);
        polyHoverDes[index].setMap(map);
        clearTimeout(this.timer);
        this.timer = setTimeout(function() {
            if (!polyHoverDes[index].getMap())
                $('#pilihkecamatan').val(poly_data_lgkp.KEC_KODE);
            set_data_chart({id_kecamatan: poly_data_lgkp.KEC_KODE, id_kelurahan: poly_data_lgkp.DESA_KODE});
            load_chart();
        }, 100);


    });
    google.maps.event.addListener(polyPathdesa[index], "mouseout", function(event) {

        marker_.setVisible(false);
        clearTimeout(this.timer);
        this.timer = setTimeout(function() {
            if (polyHoverDes[index].getMap())
                polyHoverDes[index].setMap(null);
        }, 10);

    });
    google.maps.event.addListener(polyPathdesa[index], "click", function(event) {
        //map.fitBounds(bounds);
        //map.setCenter(bounds.getCenter());
        //alert(poly_data_lgkp.KEC_KODE +" | desa : "+ poly_data_lgkp.DESA_NAMA +" | kec : "+ poly_data_lgkp.KECAMATAN_NAMA );
        console.log('set kode_kec to ' + poly_data_lgkp.KEC_KODE + ' and desa_kode to ' + poly_data_lgkp.DESA_KODE);
        $('#pilihkecamatan').val(poly_data_lgkp.KEC_KODE);
        set_data_chart({id_kecamatan: poly_data_lgkp.KEC_KODE, id_kelurahan: poly_data_lgkp.DESA_KODE});
        load_chart();

    });
    polyPathdesa[index].setMap(map);
}

function clear_layer_all(path) {
    if (path) {
        for (i in path) {
            path[i].setMap(null);
        }
    }
}

function draw_poly_desa() {
    var id_kec = document.getElementById("id_kec").value;
    $.ajax({
        type: "POST",
        url: site_url + "/map/get_polygon_desa/" + id_kec,
        dataType: 'json',
        success: function(json) {
            if (json.Desa.length > 0) {
                for (var i = 0; i < json.Desa.length; i++) {
                    var point_des = json.Desa[i];
                    add_polygon_desa(point_des, i);
                }
            }
        }
    });
    return false;
}

function add_polygon_kec(poly_data_lgkp) {
    var titik_poly = [];
    var point_label;

    var poly_data = poly_data_lgkp.KEC_POINT_LIST;
    var index = poly_data_lgkp.KEC_KODE;

    for (var a = 0; a < poly_data.length - 1; a++) {
        titik_poly[a] = new google.maps.LatLng(poly_data[a].LAT, poly_data[a].LNG);
    }

    bound_kec[index] = new google.maps.LatLngBounds();
    for (i = 0; i < titik_poly.length; i++) {
        bound_kec[index].extend(titik_poly[i]);
    }
    //console.log(bound_kec[index]);
    //alert(titik_poly);
    kecPath[index] = new google.maps.Polyline({
        path: titik_poly,
        strokeColor: '#333333',
        strokeOpacity: 0.8,
        strokeWeight: 2
    });
    kecPath[index].setMap(map);


}

function draw_poly_kec() {
    var id_kec = document.getElementById("id_kec").value;
    $.ajax({
        type: "POST",
        url: site_url + "/map/get_polygon_kec/" + id_kec,
        dataType: 'json',
        success: function(json) {
            //alert(json.Desa.length);
            if (json.Desa.length > 0) {
                for (var i = 0; i < json.Desa.length; i++) {
                    var point_kec = json.Desa[i];
                    add_polygon_kec(point_kec);
                }
            }
        }
    });
    return false;
}

